package csl.blog.server.config.thread.base;

import cn.hutool.core.util.StrUtil;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;
import java.util.UUID;

/**
 * @Description: TODO
 * @author: 隔山海
 * @date: 2022年03月26日 0:52
 */
public class QuickTaskDecorator implements TaskDecorator {

    private final String taskId = "taskId";
    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String,String> map = MDC.getCopyOfContextMap();
        return () -> {
            try {
                MDC.setContextMap(map);
                String traceId = MDC.get(taskId);
                if (StrUtil.isBlank(traceId)) {
                    insertMDC();
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }

    private void insertMDC(){
        UUID uuid = UUID.randomUUID();
        MDC.put(taskId,uuid.toString().replace("-",""));
    }
}
